//
//  XOWMTextField.m
//  sigleAPP
//
//  Created by SKL on 2017/11/10.
//  Copyright © 2017年 SKL. All rights reserved.
//

#import "XOWMTextField.h"
#import "XOWMCustomButton.h"
#import "XOWMImageView.h"
#import "NSString+category.h"

CGFloat const LEFTVIEW_HEIGHT = 30;
NSString * const YJDPhoneRegisterViewCustomKey = @"YJDPhoneRegisterViewCustomKey";
NSString * const YJDPhoneRegisterViewNotifiOb = @"YJDPhoneRegisterViewNotifiOb";
@interface XOWMTextField()<UITextFieldDelegate>
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) XOWMCustomButton *verifyBtn;//验证码按钮
@property (nonatomic, strong) CCTime *timer;
@end
@implementation XOWMTextField
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.autocorrectionType = UITextAutocorrectionTypeNo;
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.autocorrectionType = UITextAutocorrectionTypeNo;
        [self setup];
    }
    return self;
}

- (instancetype)initWithPlaceholder:(NSString *)placeholder
{
    self = [super init];
    if (self)
    {
        self.placeholder = placeholder;
        self.bounds = CGRectMake(0, 0, self.bounds.size.width - GAP * 2, TEXTFILDHEIGHT);
        self.autocorrectionType = UITextAutocorrectionTypeNo;
        [self setup];
    }
    return self;
}

- (CCTime *)timer
{
    if (!_timer)
    {
        _timer = [[CCTime alloc] init];
    }
    return _timer;
}

- (XOWMCustomButton *)rightBtn
{
    if (!_rightBtn)
    {
        _rightBtn = [[XOWMCustomButton alloc]initWithCustomIMG:@"secure" bound:CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT)];
        [_rightBtn addTarget:self action:@selector(actionShowSecureBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_rightBtn];
        NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:_rightBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:-GAP / 2.0];
        NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:_rightBtn attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:3];
        _rightBtn.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraints:@[right,centerY]];
    }
    return _rightBtn;
}

- (XOWMCustomButton *)verifyBtn
{
    if (!_verifyBtn)
    {
        _verifyBtn = [[XOWMCustomButton alloc]init];
        _verifyBtn.translatesAutoresizingMaskIntoConstraints = NO;
        _verifyBtn.backgroundColor = helperManager().getPara().color;
        [_verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_verifyBtn setTitle:@"已获取" forState:UIControlStateSelected];
        _verifyBtn.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightLight];
        [_verifyBtn addTarget:self action:@selector(yjd_actionForYanZhenBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_verifyBtn];
        
        NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:_verifyBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:_verifyBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:_verifyBtn attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:_verifyBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:200];
        [self addConstraints:@[right,top,bottom,left]];
    }
    return _verifyBtn;
}
- (UIView *)line
{
    if (!_line)
    {
        _line = [[UIView alloc]init];
        _line.backgroundColor = [UIColor lightGrayColor];
        _line.bounds = CGRectMake(0, 0, 1.0, 25);
        [self addSubview:_line];
        _line.c_left.equal(self).with.coffset(LEFTVIEW_HEIGHT + GAP);
        _line.c_centerY.equal(self);
        _line.c_size.equal(self.line.bounds.size);
 
//        _line.translatesAutoresizingMaskIntoConstraints = NO;
//        NSLayoutConstraint *centerY = [NSLayoutConstraint constraintWithItem:_line attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
//        NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:_line attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:20];
//        NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:_line attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:1];
//        NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:_line attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:25];
//        [self addConstraints:@[left,centerY,width,height]];
    }
    return _line;
}

- (void)setup
{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = GAP / 2.0;
    self.layer.borderColor = [UIColor clearColor].CGColor;
    self.layer.borderWidth = 0.5;
    self.layer.masksToBounds = YES;
    self.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.clearsOnBeginEditing = YES;//再次编辑就清空
    self.type = YJDTextFieldTypeDefault;
    self.delegate = self;
}

- (void)actionShowSecureBtn:(XOWMCustomButton *)sender
{
    sender.selected = !sender.selected;
    switch (_type)
    {
        case YJDTextFieldTypeAccountList:
        case YJDTextFieldTypeIDCart:
            sender.customIMG.imageName = (sender.selected)?@"up":@"down";
            if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(yjd_actionForXiaLa:)])
            {
                [self.customDelegate yjd_actionForXiaLa:sender.selected];
            }
            break;
        case YJDTextFieldTypePassword:
            sender.customIMG.imageName = (sender.selected)?@"secure":@"un_secure";
            self.secureTextEntry = !sender.selected;
            break;
        default:
            break;
    }
}

- (void)yjd_actionForYanZhenBtn:(XOWMCustomButton *)sender
{
        BOOL clicked = NO;
        if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(yjd_actionForVerifyCode)])
        {
            clicked = [self.customDelegate yjd_actionForVerifyCode];
            sender.selected = clicked;
            sender.backgroundColor = (sender.selected)?TEXT_GRAY_COLOR:helperManager().getPara().color;
            if (clicked)
            {
                sender.userInteractionEnabled = NO;
                [self.timer countDown:60 time:^(NSString *time) {
                    NSString *timestring = [NSString stringWithFormat:@"已获取(%@s)", time];
                    //                    DeLog(@"时间 %@",timestring);
                    [sender setTitle:timestring forState:UIControlStateSelected];
                } complete:^{
                    sender.selected = NO;
                    sender.userInteractionEnabled = YES;
                    sender.backgroundColor = (sender.selected)?TEXT_GRAY_COLOR:helperManager().getPara().color;
                }];
            }
        }
}

- (void)yjd_stopTimer
{
    if (_timer)
    {
        [_timer cancel];
        _verifyBtn.selected = NO;
        _verifyBtn.userInteractionEnabled = YES;
        _verifyBtn.backgroundColor = helperManager().getPara().color;
    }
}
//
- (void)setType:(YJDTextFieldType)type
{
    if (_type != type)
    {
        _type = type;
        self.keyboardType = (_type == YJDTextFieldTypeDefault)?UIKeyboardTypeDefault:UIKeyboardTypeASCIICapable;
        switch (_type)
        {
            case YJDTextFieldTypeDefault:
                [self yjd_setupLeftView:@"userInput"];
                break;
            case YJDTextFieldTypeAccountList:
                self.rightBtn.customIMG.imageName = @"down";
                [self yjd_setupLeftView:@"userInput"];
                break;
            case YJDTextFieldTypeAccountNormal:
                [self yjd_setupLeftView:@"userInput"];
                self.rightBtn.hidden = YES;
                self.secureTextEntry = NO;
                break;
            case YJDTextFieldTypePassword:
                self.rightBtn.customIMG.imageName = @"un_secure";
                self.secureTextEntry = YES;
                [self yjd_setupLeftView:@"pwdInput"];
                break;
            case YJDTextFieldTypeVerify:
                self.verifyBtn.hidden = NO;
                self.secureTextEntry = NO;
                [self yjd_setupLeftView:@"phone"];
                break;
            case YJDTextFieldTypePhoneNumber:
                [self setupLeftText:@"+86"];
                break;
            case YJDTextFieldTypeIDCart:
                self.rightBtn.customIMG.imageName = @"down";
                [self yjd_setupLeftView:@"userInput"];
                break;
            default:
                break;
        }
    }
}

- (void)yjd_setupRightView:(NSString *)imageName
{
    XOWMImageView *imageView = [[XOWMImageView alloc]init];
    imageView.imageName = imageName;
    imageView.bounds = CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT);
    self.rightView = imageView;
    self.rightViewMode = UITextFieldViewModeAlways;
}

- (void)yjd_setupLeftView:(NSString *)imageName
{
    XOWMImageView *imageView = [[XOWMImageView alloc]init];
    imageView.imageName = imageName;
    imageView.bounds = CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT);
    self.leftView = imageView;
    self.leftViewMode = UITextFieldViewModeAlways;
    self.line.hidden = NO;
    
}

- (void)setupLeftText:(NSString *)text
{
    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont systemFontOfSize:13 weight:UIFontWeightLight];
    label.text = text;
    label.bounds = CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT);
    self.leftView = label;
    self.leftViewMode = UITextFieldViewModeAlways;
    self.line.hidden = NO;
}

- (void)yjd_setupRightBtnTitle:(NSString *)title
{
    
}

//设置right的位置
- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    CGRect  iconRect = [super rightViewRectForBounds:bounds];
    return iconRect;
}

//设置left的位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    CGRect inset = [super leftViewRectForBounds:bounds];
    inset.origin.x += GAP / 2.0;
    return CGRectMake(5, 5, 30, 30);
    return inset;
}

//clearbutton的位置
- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    CGRect  iconRect = [super clearButtonRectForBounds:bounds];
    if (_type == YJDTextFieldTypeAccountList)  iconRect.origin.x -= 20;
    else if (_type == YJDTextFieldTypePassword) iconRect.origin.x -= 30;
    else if (_type == YJDTextFieldTypeVerify) iconRect.origin.x -= 75;
    return iconRect;
}

//阴影文字与输入框的距离
- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect inset = [super textRectForBounds:bounds];
    inset.origin.x += GAP;//文字左边与leftview右边距离10
    if (_type == YJDTextFieldTypeAccountList)  inset.size.width -= 20;
    else if (_type == YJDTextFieldTypePassword) inset.size.width -= 50;
    else if (_type == YJDTextFieldTypeVerify) inset.size.width -= 95;
    return inset;
}

//可编辑区域，光标的位置/文字的位置
- (CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect inset = [super editingRectForBounds:bounds];
    inset.origin.x += GAP;
    inset.origin.y += 1;
    if (_type == YJDTextFieldTypeAccountList)  inset.size.width -= 20;
    else if (_type == YJDTextFieldTypePassword) inset.size.width -= 30;
    else if (_type == YJDTextFieldTypeVerify) inset.size.width -= 75;
    return inset;
}

- (void)setupBorderLineWhenBeginEditing
{
    self.layer.borderColor = helperManager().getPara().color.CGColor;
}

- (void)setupBorderLineWhenEndEditing
{
    self.layer.borderColor = [UIColor clearColor].CGColor;
}

//去除text的空格
- (void)dissKongGe:(UITextField *)textField
{
    if ([textField.text containsString:@" "])
    {
        textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}

- (UIView *)yjd_findSuperView:(UIView *)view
{
    if ([view.superview isKindOfClass:NSClassFromString(@"XOWMView")])
    {
        return view.superview;
    }
    else
        return [self yjd_findSuperView:view.superview];
}

#pragma mark UITextFieldDelegate 事件
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    CGFloat maxY =  CGRectGetMaxY([textField convertRect:textField.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    UIView *keyBoard = [textField yjd_findKeyBoard];
    UIView *superView = [self yjd_findSuperView:textField];
    
    CGFloat map = SCREEN_HEIGHT - maxY - keyBoard.frame.size.height;
    if (map < 0)
    {
        [UIView animateWithDuration:0.2 animations:^{
            superView.transform = CGAffineTransformMakeTranslation(0, map);
        }];
    }

    if (self.type == YJDTextFieldTypeIDCart)//证件类型选择，输入框不可编辑
        return NO;
    
    [self setupBorderLineWhenBeginEditing];
    
    if (_type == YJDTextFieldTypeAccountList && self.rightBtn.selected)//输入账户时,如果下拉列表正显示，隐藏下拉列表
    {
        [self performSelector:@selector(actionShowSecureBtn:) withObject:self.rightBtn];
    }
    else if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)])
        return [self.customDelegate textFieldShouldBeginEditing:textField];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self resignFirstResponder];
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textFieldShouldReturn:)])
        return [self.customDelegate textFieldShouldReturn:textField];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
    [self dissKongGe:textField];
    
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textField: shouldChangeCharactersInRange: replacementString:)])
        return [self.customDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    if (![string isEqualToString:tem])
    {
        return NO;
    }
    return YES;
}   // return NO to not change text

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UIView *superView = [self yjd_findSuperView:textField];
    [UIView animateWithDuration:0.2 animations:^{
        superView.transform = CGAffineTransformIdentity;
    }];
    
    [self dissKongGe:textField];
    [self setupBorderLineWhenEndEditing];
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textFieldDidEndEditing:)])
        [self.customDelegate textFieldDidEndEditing:textField];
}

//- (void)dealloc
//{
//    []
//}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */



- (void)sp_getLoginState {
    NSLog(@"Get Info Success");
}
@end
